package com.itheima.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 公共字段自动填充
 *
 * @author hua
 * @since 2022/11/2 10:46
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入操作,自动填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        long threadId = Thread.currentThread().getId();
        log.info("公共字段自动填充 ===> 当前执行ID ===> {}",threadId);
        //赋值
        //第一个参数,是字段
        //第二个参数，是要赋值的内容
        Long currentUserId = BaseContext.getCurrentUserId();
        LocalDateTime now = LocalDateTime.now();
        //创建时间
        metaObject.setValue("createTime",now);
        //修改时间
        metaObject.setValue("updateTime",now);
        //创建人ID
        metaObject.setValue("createUser",currentUserId);
        //修改人ID
        metaObject.setValue("updateUser",currentUserId);
    }

    /**
     * 修改操作,自动填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
      log.info("公共字段自动填充");
      metaObject.setValue("updateTime",LocalDateTime.now());
      metaObject.setValue("updateUser",BaseContext.getCurrentUserId());
    }
}
